package com.syb.dao.impl;

import java.util.ArrayList;
import java.util.List;

import org.hibernate.FlushMode;
import org.springframework.stereotype.Repository;

import com.syb.dao.LoginDao;
import com.syb.entity.function.SysResource;
import com.syb.entity.function.SysRole;
import com.syb.entity.user.RelUserRole;
import com.syb.entity.user.SysUser;
import com.syb.util.BaseDao;

@Repository
public class LoginDaoImpl extends BaseDao implements LoginDao {

	public List<SysUser> querySysUser(String name, String password) throws Exception {
		String[] param = new String[]{name,password};
		
		List<SysUser> sysUser = new ArrayList<SysUser>();
		try{
		 sysUser = (List<SysUser>)this.getHibernateTemplate().find(" from SysUser where sysName=? and sysPassword=?", param);
		
		}catch(Exception e){
			throw new Exception(e.getMessage());
		}
		return sysUser;
	}

	/**
	 * 查询资源
	 */
	public List<SysResource> querySysResource(final Integer id) throws Exception {
		List<SysResource> sysResourceList = new ArrayList<SysResource>();
		final String sql = ""
				+ " SELECT DISTINCT(s.id) as ids,s.* from sys_resource s "
				+ " LEFT JOIN rel_sys_role_resource as relr on s.id=relr.rel_sys_resource_id "
				+ " LEFT JOIN sys_role as role on role.id= relr.rel_sys_role_id "
				+ " LEFT JOIN rel_sys_user_role as relsys on relsys.rel_sys_role_id = role.id "
				+ " LEFT JOIN sys_user as u on u.id=relsys.rel_sys_user_id where role.`status`=1 and u.id=? ";
		try{
			sysResourceList =(List<SysResource>)this.getSessionFactory().getCurrentSession().createSQLQuery(sql).addEntity(SysResource.class).setParameter(0, id).list();
		}catch(Exception e){
			throw new Exception(e.getMessage());
		}
		return sysResourceList;
	}

	/**
	 * 查询角色
	 */
	public List<SysRole> querySysRole(Integer id) throws Exception {
		List<SysRole> sysRole = new ArrayList<SysRole>();
		String sql = "select s.* from  sys_role as s  left join  rel_sys_user_role as r on s.id = r.rel_sys_role_id "
				+ "left join sys_user as su  on su.id = r.rel_sys_user_id  where su.id = ? ";
		try{
			sysRole = (List<SysRole>)this.getSessionFactory().getCurrentSession().createSQLQuery(sql).addEntity(SysRole.class).setParameter(0, id).list();
		}catch(Exception e){
			throw new Exception(e.getMessage());
		}
		return sysRole;
	}

}
